package edu.uit.se.slgroup.construct.dao;

import java.io.Serializable;
import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import edu.uit.se.slgroup.construct.domain.User;


public class UserDaoImpl implements UserDao{

	@Autowired
	SessionFactory sessionFactory;
	
	/**
	 * Chu y cac phuong thuc ke thua nen de Override
	 * Tranh truong hop khong hien thi du lieu
	 */
	
 
	@Transactional
	public int insertUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(user);
		tx.commit();
		Serializable id = session.getIdentifier(user);
		session.close();
		return (Integer)id;
	}
 
	public List<User> getUserList() {
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<User> userList = session.createQuery("from User").list();
		session.close();
		return userList;
	}

 
	public User getUserById(int id) {
		Session session = sessionFactory.openSession();
		User user = (User) session.load(User.class, id);
		//dong ket noi, nhieu truong hop khong lay duoc obj
		//session.close();
		return user;
	}
 
	public int updateUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(user);
		tx.commit();
		Serializable id = session.getIdentifier(user);
		session.close();
		return (Integer)id;		
	}

 
	public int deleteUser(int id) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		User user = (User) session.load(User.class, id);
		session.delete(user);
		tx.commit();
		Serializable ids = session.getIdentifier(user);
		session.close();
		return (Integer) ids;
	}

	 
}
